package srzy.common

import scala.util.parsing.combinator._

object CdrFieldParser extends RegexParsers {

  def ` ` = """[ ]+""".r
  def `+-` = """[+-]""".r

  def str: Parser[String] = """[A-Za-z0-9]*""".r ^^ { _.toString }
  def int: Parser[Int] = """[0-9]*""".r ^^ { _.toInt }
  def group1: Parser[(String, (String, List[Int]))] = str ~ `+-` ~ repsep(int, "|") ^^
    { case s ~ f ~ i => (s, (f, i.toList.sorted)) }
  def group2: Parser[(String, Map[String, (String, List[Int])])] = str ~ ":" ~ repsep(group1, ";") ^^
    { case s ~ _ ~ g => (s, g.toMap) }

  def group3: Parser[Map[String, Map[String, (String, List[Int])]]] = repsep(group2, "^") ^^
    { case s => s.toMap }

  def parse(text: String): Map[String, Map[String, (String, List[Int])]] = {
    parseAll(group3, text) match {
      case Success(r, _) => r
      case Failure(msg, _) => throw new Exception("YAML Parser failure :" + msg)
      case Error(msg, _) => throw new Exception("YAML Parser error :" + msg)
    }
  }

}